<?php

namespace app\api\model\dealer;

use app\common\model\dealer\Order as OrderModel;
use app\common\service\Order as OrderService;
use app\common\enum\OrderType as OrderTypeEnum;
use app\common\library\MysicLog;
use think\Db;
/**
 * 分销商订单模型
 * Class Apply
 * @package app\api\model\dealer
 */
class Order extends OrderModel
{


    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'update_time',
    ];

    /**
     * 获取分销商订单列表
     * @param $user_id
     * @param int $is_settled
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($user_id, $is_settled = -1)
    {
        $is_settled > -1 && $this->where('is_settled', '=', !!$is_settled);
        $data = $this->with(['user'])
            ->where('first_user_id|second_user_id|third_user_id', '=', $user_id)
            ->where(['first_money'=>['>',0]])
            ->order(['create_time' => 'desc'])
            ->paginate(15, false, [
                'query' => \request()->request()
            ]);
        if ($data->isEmpty()) {
            return $data;
        }

        // 整理订单信息
        $with = ['goods' => ['image', 'refund'], 'address', 'user'];
        $with2 = ['orderplan' => ['image'], 'address', 'user'];
        $with3 = ['goods' => ['image'], 'user'];
        return OrderService::getOrderList($data, 'order_master', $with,$with2,$with3);
    }


    // +----------------------------------------------------------------------
    // | 创建商品分销商订单记录
    // +----------------------------------------------------------------------


    /**
     * 创建商品分销商订单记录--方案一
     * @param $order
     * @param int $order_type 订单类型 (10商城订单 20拼团订单)
     * @return bool|false|int
     * @throws \think\exception\DbException
     */
    public static function createOrder(&$order, $refereeId,$order_type = OrderTypeEnum::MASTER)
    {

        $log = MysicLog::instance();
        $log->setFilename('prepay/buynow');

        // 分销订单模型
        $model = new self;

        // 计算订单分销佣金
        $capital = $model->getCapitalByOrder($order);
        $log->info($capital, '获取分销佣金结果');
        $first_money = bcsub($capital['first_money'], 0, 2);
        $log->info($first_money, '获取一级分销佣金结果');
        if($first_money>0){
            $data = [
                'user_id' => $order['user_id'],//用户id (买家)
                'order_id' => $order['order_id'],//订单id
                'order_type' => $order_type,//订单类型(10商城订单 20拼团订单 30 购买vip 40 购买爆品礼 50 当面付 60分红转化)
                'order_price' => $capital['orderPrice'],//订单总金额
                'first_user_id' => $refereeId,//分销商用户id(一级)
                'second_user_id' => 0,//分销商用户id(二级)
                'third_user_id' => 0,//分销商用户id(三级)
                'first_money' => $first_money,//分销佣金(一级)
                'second_money' => 0,//分销佣金(二级)
                'third_money' => 0,//分销佣金(三级)
                'is_invalid' => 0,//订单是否失效(0未失效 1已失效)
                'is_settled' => 0,//是否已结算佣金(0未结算 1已结算)
                'settle_time' => 0,//结算时间
                'wxapp_id' => $order['wxapp_id'],//小程序id
                'create_time' => time(),//创建时间
                'update_time' => time(),//更新时间
                'dealer_case' =>  1,//分销方案
            ];
            $log->info($data, '分销订单加入数据');
            $dealer_id = Db::name('dealer_order')->insertGetId($data);
            $log->info($dealer_id, '获取分销订单id');
            return $dealer_id;

        }

    }




    /**
     * 创建商品分销商订单记录--方案二
     * @param $order
     * @param int $order_type 订单类型 (10商城订单 20拼团订单)
     * @return bool|false|int
     * @throws \think\exception\DbException
     */
    public static function createOrderTow(&$order, $refereeId,$checkDealerTow,$order_type = OrderTypeEnum::MASTER)
    {
        $log = MysicLog::instance();
        $log->setFilename('prepay/buynow');
        // 分销订单模型
        $model = new self;
        // 计算订单分销佣金
        $capital = $model->getCapitalByOrderTow($order,$checkDealerTow);
        $log->info($capital, '获取分销佣金结果');
        $first_money = bcsub($capital['first_money'], 0, 2);
        $log->info($first_money, '获取二级分销佣金结果');
        if($first_money>0){

            $data = [
                'user_id' => $order['user_id'],//用户id (买家)
                'order_id' => $order['order_id'],//订单id
                'order_type' => $order_type,//订单类型(10商城订单 20拼团订单 30 购买vip 40 购买爆品礼 50 当面付 60分红转化)
                'order_price' => $capital['orderPrice'],//订单总金额
                'first_user_id' => $refereeId,//分销商用户id(一级)
                'second_user_id' => 0,//分销商用户id(二级)
                'third_user_id' => 0,//分销商用户id(三级)
                'first_money' => $first_money,//分销佣金(一级)
                'second_money' => 0,//分销佣金(二级)
                'third_money' => 0,//分销佣金(三级)
                'is_invalid' => 0,//订单是否失效(0未失效 1已失效)
                'is_settled' => 0,//是否已结算佣金(0未结算 1已结算)
                'settle_time' => 0,//结算时间
                'wxapp_id' => $order['wxapp_id'],//小程序id
                'create_time' => time(),//创建时间
                'update_time' => time(),//更新时间
                'dealer_case' =>  2,//分销方案
            ];
            $log->info($data, '分销订单加入数据');
            $dealer_id = Db::name('dealer_order')->insertGetId($data);
            $log->info($dealer_id, '获取分销订单id');
            return $dealer_id;

        }

    }




    // +----------------------------------------------------------------------
    // | 创建爆品礼分销商订单记录
    // +----------------------------------------------------------------------


    /**
     * 创建爆品礼分销商订单记录
     * @param $order
     * @param int $order_type 订单类型 (10商城订单 20拼团订单)
     * @return bool|false|int
     * @throws \think\exception\DbException
     */
    public static function createGiftsOrder(&$order,$dealer_case,$order_type,$flow_type)
    {

        MysicLog::instance()->info($order['gifts_distribution_price'], '创建爆品礼分销订单，获取分销金额');

        try{
            // 分销订单模型
            $model = new self;
            $status = $model->save([
                'user_id' => $order['user_id'],
                'order_id' => $order['order_id'],
                'order_type' => $order_type,
                'order_price' => $order['gifts_price'],
                'first_money' => $order['gifts_distribution_price'],
                'second_money' => 0,
                'third_money' => 0,
                'first_user_id' => $order['superior_user_id'],
                'second_user_id' => 0,
                'third_user_id' => 0,
                'wxapp_id' => $order['wxapp_id'],
                'dealer_case' =>  $dealer_case,
            ]);
            MysicLog::instance()->info($status, '创建爆品礼分销订单');
            if($status){
                OrderModel::grantGiftsMoney($order,$order_type,$flow_type);
            }
        } catch(\Exception $e) {

            MysicLog::instance()->error(exceptionLogFormat($e), '创建爆品礼分销订单错误');
        }


    }


    // +----------------------------------------------------------------------
    // | 创建当面付分销商订单记录
    // +----------------------------------------------------------------------


    /**
     * 创建当面付订单记录
     * @param $order
     * @param int $order_type
     * @return bool|false|int
     * @throws \think\exception\DbException
     */
    public static function createFaceOrder(&$order,$consume_charge,$upUserId,$wxapp_id,$order_type,$flow_type,$dealer_case){


        // 分销订单模型
        $model = new self;
        try{

            $first_money = bcmul($consume_charge/100, $order['order_price'],2);
            MysicLog::instance()->info($first_money, '创建当面付分销订单记录，获取分销金额');

            if($first_money>0){
                $status = $model->save([
                    'user_id' => $order['user_id'],
                    'order_id' => $order['order_id'],
                    'order_type' => $order_type,
                    'order_price' => $order['order_price'],
                    'first_money' => $first_money,
                    'second_money' => 0,
                    'third_money' => 0,
                    'first_user_id' => $upUserId,
                    'second_user_id' => 0,
                    'third_user_id' => 0,
                    'is_settled' => 0,
                    'wxapp_id' => $wxapp_id,
                    'dealer_case' => $dealer_case,
                ]);
                MysicLog::instance()->info($status, '创建当面付分销订单结果');
                if($status){
                    OrderModel::grantGiftsMoney($order,$order_type,$flow_type);
                }
            }
        } catch(\Exception $e) {

            MysicLog::instance()->error(exceptionLogFormat($e), '创建当面付分销订单错误');
        }



    }





    // +----------------------------------------------------------------------
    // | 创建储值卡分销商订单记录
    // +----------------------------------------------------------------------


    /**
     * 创建储值卡分销商订单记录
     * @param $order
     * @param int $order_type
     * @return bool|false|int
     * @throws \think\exception\DbException
     */
    public static function createVipOrder(&$order, $refereeId,$order_id,$order_type = OrderTypeEnum::VIPPAY)
    {

        $log = MysicLog::instance();
        $log->setFilename('prepay/vipcard');

        // 分销订单模型
        $model = new self;

        // 计算订单分销佣金
        $capital = $model->getCapitalVipByOrder($order);
        $log->info($capital, '获取分销佣金结果');
        $first_money = bcsub($capital['first_money'], 0, 2);
        $log->info($first_money, '获取一级分销佣金结果');
        if($first_money>0){
            $data = [
                'user_id' => $order['order']['user_id'],//用户id (买家)
                'order_id' => $order_id,//订单id
                'order_type' => 30,//订单类型(10商城订单 20拼团订单 30 购买vip 40 购买爆品礼 50 当面付 60分红转化)
                'order_price' => $capital['orderPrice'],//订单总金额
                'first_user_id' => $refereeId,//分销商用户id(一级)
                'second_user_id' => 0,//分销商用户id(二级)
                'third_user_id' => 0,//分销商用户id(三级)
                'first_money' => $first_money,//分销佣金(一级)
                'second_money' => 0,//分销佣金(二级)
                'third_money' => 0,//分销佣金(三级)
                'is_invalid' => 0,//订单是否失效(0未失效 1已失效)
                'is_settled' => 0,//是否已结算佣金(0未结算 1已结算)
                'settle_time' => 0,//结算时间
                'wxapp_id' => $order['order']['wxapp_id'],//小程序id
                'create_time' => time(),//创建时间
                'update_time' => time(),//更新时间
                'dealer_case' =>  1,//分销方案
            ];
            $log->info($data, '分销订单加入数据');
            $dealer_id = Db::name('dealer_order')->insertGetId($data);
            $log->info($dealer_id, '获取分销订单id');
            return $dealer_id;
        }else{
            return true;
        }

    }


    /**
     * 创建储值卡分销商订单记录
     * @param $order
     * @param int $order_type
     * @return bool|false|int
     * @throws \think\exception\DbException
     */
    public static function createVipOrderTow(&$order, $refereeId,$order_id,$checkDealerTow,$order_type = OrderTypeEnum::VIPPAY)
    {

        $log = MysicLog::instance();
        $log->setFilename('prepay/vipcard');
        // 分销订单模型
        $model = new self;
        // 计算订单分销佣金
        $capital = $model->getCapitalVipByOrderTow($order,$checkDealerTow);
        $log->info($capital, '获取分销佣金结果');
        $first_money = bcsub($capital['first_money'], 0, 2);
        $log->info($first_money, '获取一级分销佣金结果');
        if($first_money>0){

            $data = [
                'user_id' => $order['order']['user_id'],//用户id (买家)
                'order_id' => $order_id,//订单id
                'order_type' => 30,//订单类型(10商城订单 20拼团订单 30 购买vip 40 购买爆品礼 50 当面付 60分红转化)
                'order_price' => $capital['orderPrice'],//订单总金额
                'first_user_id' => $refereeId,//分销商用户id(一级)
                'second_user_id' => 0,//分销商用户id(二级)
                'third_user_id' => 0,//分销商用户id(三级)
                'first_money' => $first_money,//分销佣金(一级)
                'second_money' => 0,//分销佣金(二级)
                'third_money' => 0,//分销佣金(三级)
                'is_invalid' => 0,//订单是否失效(0未失效 1已失效)
                'is_settled' => 0,//是否已结算佣金(0未结算 1已结算)
                'settle_time' => 0,//结算时间
                'wxapp_id' => $order['order']['wxapp_id'],//小程序id
                'create_time' => time(),//创建时间
                'update_time' => time(),//更新时间
                'dealer_case' =>  2,//分销方案
            ];

            $log->info($data, '分销订单加入数据');
            $dealer_id = Db::name('dealer_order')->insertGetId($data);
            $log->info($dealer_id, '获取分销订单id');
            return $dealer_id;
        }else{
            return true;
        }

    }




    /**
     * 获取当前买家的所有上级分销商用户id
     * @param $user_id
     * @param $level
     * @param $self_buy
     * @return mixed
     * @throws \think\exception\DbException
     */
    private function getDealerUserId($user_id, $level, $self_buy)
    {
        $dealerUser = [
            'first_user_id' => $level >= 1 ? Referee::getRefereeUserId($user_id, 1, true) : 0,
            'second_user_id' => $level >= 2 ? Referee::getRefereeUserId($user_id, 2, true) : 0,
            'third_user_id' => $level == 3 ? Referee::getRefereeUserId($user_id, 3, true) : 0
        ];
        // 分销商自购
        if ($self_buy && User::isDealerUser($user_id)) {
            return [
                'first_user_id' => $user_id,
                'second_user_id' => $dealerUser['first_user_id'],
                'third_user_id' => $dealerUser['second_user_id'],
            ];
        }
        return $dealerUser;
    }

}
